#!/bin/bash
# -*- mode: shell-script; indent-tabs-mode: nil; sh-basic-offset: 4; -*-
# ex: ts=8 sw=4 sts=4 et filetype=sh

set -e

# Generators don't have logging right now
# https://github.com/systemd/systemd/issues/15638
exec 1>/dev/kmsg; exec 2>&1

UNIT_DIR="${1:-/tmp}"

cmdline=( $(</proc/cmdline) )
karg() {
    local name="$1" value="$2"
    for arg in "${cmdline[@]}"; do
        if [[ "${arg%%=*}" == "${name}" ]]; then
            value="${arg#*=}"
        fi
    done
    echo "${value}"
}

karg_bool() {
    local value=$(karg "$@")
    case "$value" in
        ""|0|no|off) return 1;;
        *) return 0;;
    esac
}

if [ -n "$(karg nestos.inst.install_dev)" -o \
     -n "$(ls -A /etc/nestos/installer.d 2>/dev/null)" ]; then
    ln -sf "/usr/lib/systemd/system/nestos-installer-post.target" \
        "${UNIT_DIR}/default.target"

    # Create precondition for nestos-installer-reboot.service if requested
    if ! karg_bool nestos.inst.skip_reboot; then
        touch /run/nestos-installer-reboot
    fi
fi
